#include "cataloguewgt.h"
#include "ui_cataloguewgt.h"
#include "cataloguelistmodel.h"
#include "contentinfo.h"

#include <QDebug>
#include <QModelIndex>

CatalogueWgt::CatalogueWgt(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CatalogueWgt)
{
    ui->setupUi(this);

    _model = new CatalogueListModel(this);

    ui->listView->setModel(_model);

    initStyle();
    initConnect();
}

CatalogueWgt::CatalogueWgt(const QString &filePath, QWidget *parent) : CatalogueWgt(parent)
{
    setFile(filePath);
}

CatalogueWgt::~CatalogueWgt()
{
    delete ui;
}

void CatalogueWgt::setFile(const QString &filePath)
{
    _filePath = filePath;
    analyzeAhapter();
}

QString CatalogueWgt::file()
{
    return _filePath;
}

CatalogueItem CatalogueWgt::getCatalogueItem(int index)
{
    return _model->item(index);
}

CatalogueItem CatalogueWgt::getCurrentItem()
{
    return _model->item(ui->listView->currentIndex().row());
}

void CatalogueWgt::initStyle()
{

}

void CatalogueWgt::initConnect()
{
    connect(ui->listView, &QListView::clicked, this, &CatalogueWgt::itemClickedSlt);
}

void CatalogueWgt::itemClickedSlt(const QModelIndex &index)
{
    if(!index.isValid()) return;
    Q_EMIT chapterClickedSgl(_model->item(index.row()));
}

void CatalogueWgt::analyzeAhapter()
{
    if(!QFile::exists(_filePath)) return;
    ContentInfo info(_filePath, this);
    _model->setDataList(info.readCatalogue());
    ui->listView->setCurrentIndex(_model->index(0));
    Q_EMIT analyzeAhapterFinishedSgl();
}
